<template>
  <hu-card class="box_card">
    <el-row :gutter="10" type="flex" style="margin: 0;">
      <el-button  icon="el-icon-plus" type="primary" @click="handleAdd" style="font-size: 14px;">添加菜单</el-button>

      <el-button  type="primary" @click="toggleRowExpansion" style="font-size: 14px;margin-left:10px">
        全部{{ isExpansion ? "收缩" : "展开" }}
      </el-button>
    </el-row>

    <el-table style="margin-top: 20px" v-if="refreshTable" v-loading="loading" height="680" :data="menuList" ref="tableList" border row-key="code" :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <i v-if="scope.row.iconType == 2 && scope.row.icon" :class="scope.row.icon" />
          <svg-icon v-if="scope.row.iconType == 1 && scope.row.icon" :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="order" label="排序" width="60"></el-table-column>
      <el-table-column prop="code" label="权限标识" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="id" label="id"></el-table-column>
      <el-table-column prop="path" label="路由" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="hide" label="状态" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.hide">
            <el-button  round plain type="danger">禁用</el-button>
          </span>
          <span v-else>
            <el-button  round plain type="success">启用</el-button>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <hu-modal :title="title" :show-modal.sync="open" :loading="MixinLoading" @submit="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect v-model="form.parentCode" :options="menuOptions" @input="updateValue" :normalizer="normalizer" :show-count="true" placeholder="选择上级菜单" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">目录</el-radio>
                <el-radio :label="2">菜单</el-radio>
                <el-radio :label="3">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type != '3'">
            <el-form-item label="图标类型" prop="type">
              <el-radio-group v-model="form.iconType">
                <el-radio label="1">原生</el-radio>
                <el-radio label="2">自定义</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.iconType == 1">
            <el-form-item v-if="form.type != '3'" label="菜单图标">
              <el-popover placement="bottom-start" width="550" trigger="click" @show="$refs['iconSelect'].reset()">
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标">
                  <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" style="height: 32px; width: 16px" />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.iconType == 2">
            <el-form-item label="菜单图标" v-if="form.type != '3'">
              <el-input v-model="form.icon" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="order">
              <el-input-number v-model="form.order" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.type == '1'">
            <el-form-item label="组件路径" prop="type">
              <el-radio-group v-model="form.component">
                <el-radio label="Layout">一级目录</el-radio>
                <el-radio label="ParentView">二级</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.type != 3" prop="path" label="路由地址">
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '2'">
            <el-form-item prop="component">
              <span slot="label">
                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-input v-model="form.code" placeholder="请输入权限标识" maxlength="100" />
              <span slot="label">
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                权限字符
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                显示状态
              </span>
              <el-radio-group v-model="form.hide">
                <el-radio v-for="dict in sys_show_hide" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </hu-modal>
  </hu-card>
</template>

<script>
import { listMenu, delMenu, addMenu, updateMenu } from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";

export default {
  name: "SystemMenu",
  components: { Treeselect, IconSelect },
  data() {
    return {
      isExpansion: false,
      sys_show_hide: [
        { value: false, label: "显示" },
        { value: true, label: "隐藏" },
      ],
      // 遮罩层
      loading: false,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
        order: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    updateValue(code) {
      if (!this.form.id) {
        this.$set(this.form, "code", code + ":");
      }
    },
    // 切换数据表格树形展开
    toggleRowExpansion() {
      this.isExpansion = !this.isExpansion;
      this.toggleRowExpansionAll(this.menuList, this.isExpansion);
    },
    toggleRowExpansionAll(data, isExpansion) {
      data.forEach((item) => {
        this.$refs.tableList.toggleRowExpansion(item, isExpansion);
        if (item.children !== undefined && item.children !== null) {
          this.toggleRowExpansionAll(item.children, isExpansion);
        }
      });
    },
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listMenu({
        menuName: undefined,
        visible: undefined,
      }).then((response) => {
        this.loading = false;
        this.menuList = [response.result];
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.code,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      this.menuOptions = [];
      listMenu().then((response) => {
        this.menuOptions = [response.result];
      });
    },
    // 表单重置
    reset() {
      this.form = {
        code: "",
        name: "",
        order: 0,
        type: 1,
        hide: false,
        icon: "",

        iconType: "1",
        path: "",
        component: "",
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();

      this.open = true;
      this.title = "添加菜单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.form = this.deepClone(row);
      this.form.newCode = this.form.code;
      this.open = true;
      this.title = "修改菜单";
    },
    deepClone(object) {
      let str;
      let newobj = object.constructor === Array ? [] : {};
      if (typeof object !== "object") {
        return object;
      } else if (window.JSON) {
        str = JSON.stringify(object);
        newobj = JSON.parse(str);
      } else {
        for (const i in object) {
          if (Object.prototype.hasOwnProperty.call(object, object[i])) {
            newobj[i] =
              typeof object[i] === "object"
                ? this.deepClone(object[i])
                : object[i];
          }
        }
      }
      return newobj;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            if (this.form.newCode == this.form.code) {
              this.form.newCode = "";
            } else {
              let str = this.form.newCode;
              this.form.newCode = this.form.code;
              this.form.code = str;
            }
            let params = {
              ...this.form,
            };
            updateMenu(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let params = {
              ...this.form,
            };
            addMenu(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delMenu({ codes: [row.code] });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.box_card {
  height: calc(100vh - 150px);
  overflow: auto;
}
</style>
